﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace CXMLStudioIDE.Common
{
    public class FindMembersClass
    {
        #region Declarations

        string szResults = "";
        public static DependencyCollection dcDependencies = new DependencyCollection();

        #endregion

        #region Methods

        public string FindMembers(Type objType)
        {            
            /*  Retrieve dependent classes */
            MemberInfo[] arrayMemberInfo;
            try
            {
                AddBaseTypeDependency(objType.BaseType);
                arrayMemberInfo = objType.FindMembers(MemberTypes.Property | MemberTypes.Custom | MemberTypes.TypeInfo | MemberTypes.Field | MemberTypes.NestedType , BindingFlags.Public | BindingFlags.Static| BindingFlags.Instance | BindingFlags.NonPublic  , new MemberFilter(DelegateToSearchCriteria), "Property");                                
            }
            catch (Exception e)
            {
                szResults += ("Exception : " + e.ToString() );            
            }        
            return szResults;

        }

        private void AddBaseTypeDependency(Type tBaseType)
        {
            Dependency depEntity = new Dependency();
            depEntity.EntityName = tBaseType.Name.ToString();
            dcDependencies.Add(depEntity);
            if (tBaseType.BaseType.FullName.ToString() != "System.Object" && tBaseType.BaseType.FullName.ToString() != null)
            {
                AddBaseTypeDependency(tBaseType.BaseType);
            }
        }

        public static bool DelegateToSearchCriteria(MemberInfo objMemberInfo, Object objSearch)
        {
            System.Reflection.PropertyInfo info = (objMemberInfo as PropertyInfo);
            
            // Compare the name of the member function with the filter criteria.
            if(objMemberInfo.MemberType.ToString() == objSearch.ToString() && info.PropertyType.FullName != "System.String" )                                                                
            {
                /* any type that is subtyped to other the system.string, may need to expand to those that are in Enterprise namespace*/                                
                Dependency depEntity = new Dependency();
                depEntity.EntityName = info.PropertyType.Name.ToString();
                dcDependencies.Add(depEntity);
                return true;
            }
            else 
            {
                return false;
            }
        }

        #endregion
    }
}
